import {
	HTTP_REQUEST_URL,
	HEADER,
	TOKENNAME,
} from '@/config/app.js'; 

import $Cache from './cache.js'

import {
	toLogin,
	checkLogin
} from '@/libs/login';

import store from "../store";
/**
 * 发送请求
 */
function baseRequest(url, method, data, {
	// 不验证登录
	noAuth = false,
	// 不验证状态
	noVerify = false,
	// 加载动画
	loading = false,
	// // 不做缓存
	// isCache = false,
	// // 缓存多久
	// expires_time = 30
}) {
	let Url = HTTP_REQUEST_URL,header = HEADER;
		
	const pages = getCurrentPages()
	const prePage = pages[pages.length - 1]
	const current_page = prePage.route
	// console.log('当前路由地址', prePage.route);
	if(loading){
		uni.showLoading({
		title: '加载中'
		});
	}
	if (!noAuth) {
		//登录过期自动登录
		if (!store.getters.token) {
			
			if (current_page != 'pages/users/login/login') {
				toLogin();
			}
			
			uni.showToast({
				title: '登录状态已过期',
				icon: 'none'
			})
			return Promise.reject({
				msg: '未登录'
			});
		}
	}
	if (store.getters.token) header[TOKENNAME] = 'Bearer ' + store.getters.token;
	
	return new Promise((reslove, reject) => {
		
		uni.request({
			url: Url + url,
			method: method || 'GET',
			header: header,
			data: data || {},
			success: (res) => {
				// console.log('res',res)
				if (noVerify) {
					reslove(res.data, res);
				} else if (res.data.status == 200) {
					reslove(res.data, res);
				} else if ([110002, 110003, 110004, 410000].indexOf(res.data.status) !== -1) {
					// if (current_page != 'pages/users/login/login' && !checkLogin()) {
					// 	toLogin();
					// }
					uni.showToast({
						title: res.data.msg,
						icon: 'none'
					})
					reject(res.data);
				} else if (res.data.status == 400) {
					uni.$u.toast(res.data.msg)
					reject(res.data);
				} else if (res.data.status == 100103) {
					uni.showModal({
						title: `提示`,
						content: res.data.msg,
						showCancel: false,
						confirmText: `我知道了`
					});
				} else
					reject(res.data.msg || `系统错误`);
			},
			fail: (msg) => {
				let data = {
					mag: `请求失败`,
					status: 1 //1没网
				}
				reject(data);
			},
			complete:()=>{
				uni.hideLoading();
			}
		})
	});
}

const request = {};

['options', 'get', 'post', 'put', 'head', 'delete', 'trace', 'connect'].forEach((method) => {
	request[method] = (api, data, opt) => baseRequest(api, method, data, opt || {})
});



export default request;